<template>
  <el-dialog
    v-model="dialogShow"
    :close-on-click-modal="false"
    :destroy-on-close="false"
    custom-class="mydialog"
    width="1000px"
    title="变更终端配送信息"
    @close="close"
  >
    <div class="distribute-info">

      <el-form
        ref="formRef"
        :model="formData"
        :label-width="formLabelWidth"
        size="small"
        :rules="formRules"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <item-title title="选择变更后使用的新配送服务" />
          </el-col>
          <el-col :span="12">
            <el-form-item label="配送模式">
              <el-select
                v-model="formData.rddType"
                placeholder="请选择配送模式"
                style="width: 100%;"
                @change="distributeModeChange"
              >
                <el-option
                  v-for="item in distributeModeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="配送产品信息"
              prop="productId"
            >
              <el-select
                v-model="formData.productId"
                placeholder="请选择配送产品"
                clearable
                style="width: 100%;"
                @change="productSelectChange"
              >
                <el-option
                  v-for="item in productOptions"
                  :key="item.id"
                  :label="`${item.productPopularName}-${item.approvalNumber}-${item.packSpecs}`"
                  :value="item.id"
                >
                  <div class="pro-item">
                    <span>{{ item.productPopularName }}-{{ item.approvalNumber }}-{{ item.packSpecs }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col
            v-if="formData.rddType==='2'"
            :span="12"
          >
            <el-form-item
              label="配送商名称"
              :prop="formData.rddType==='2'?'distributeId':'normal'"
            >
              <div style="width: 100%;">
                <el-select
                  v-model="formData.distributeId"
                  placeholder="请选择当前配送商或可更换配送商"
                  clearable
                  style="width: 100%;"
                  :disabled="formData.productId?false:true"
                  @change="distributorChange"
                >
                  <el-option
                    v-for="item in distributorOptions"
                    :key="item.id"
                    :label="`${item.distributeName}`"
                    :value="item.id"
                  >
                    <div class="pro-item">
                      <span>{{ item.distributeName }}</span>
                    </div>
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
          </el-col>
          <el-col
            v-if="formData.rddType==='2'"
            :span="12"
          >
            <el-form-item
              label="配送费"
              :prop="formData.rddType==='2'?'distributeDetailId':'normal'"
            >
              <distribute-price-popover
                ref="pricePopoverRef"
                :datas="{
                  productId: formData.productId,
                  distributeId: formData.distributeId,
                }"
                position="bottom-start"
                @confirm="selectPrice"
              >
                <div style="display:flex;flex-wrap:nowrap;">
                  <el-select
                    v-model="formData.distributePrice"
                    style="flex:1;"
                    placeholder="选择配送费"
                    clearable
                    :disabled="formData.productId&&formData.distributeId?false:true"
                    @focus="priceFocus"
                    @change="distributePriceChange"
                  >
                    <template #empty />
                  </el-select>
                  <div v-if="distributePriceInfo?.computeMode==='固定价格'">
                    <span
                      v-if="formData.sellUnit"
                      style="margin-left:4px;"
                    >元 / {{ getLabel('sell_unit',formData.sellUnit) }}</span>
                  </div>
                  <div v-if="distributePriceInfo?.computeMode==='终端价百分比'">%终端价</div>
                </div>
              </distribute-price-popover>
            </el-form-item>
          </el-col>
          <el-col
            v-if="formData.rddType==='2'&&distributePriceInfo"
            :span="12"
          >
            <el-form-item label="配送地区">
              <area-list-view :areas="distributePriceInfo?.region" />
            </el-form-item>
          </el-col>
          <el-col
            v-if="formData.rddType==='2'&&distributePriceInfo"
            :span="12"
          >
            <el-form-item label="配送服务编号">
              <div>{{ distributePriceInfo?.distributeServeNo }}</div>
            </el-form-item>
          </el-col>
          <el-col
            v-if="formData.rddType==='2'&&distributePriceInfo"
            :span="12"
          >
            <el-form-item label="服务结束日期">
              <div><span>{{ dateFormat('yyyy-mm-dd HH:MM',distributePriceInfo?.expireTime) }}</span></div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <item-title title="选择此配送商下需要变更的交易终端" />
          </el-col>
          <div style="width:100%;margin-bottom:20px">
            <el-col :span="12">
              <el-button
                type="primary"
                size="mini"
                @click="addTerminal"
              >添加终端</el-button>
              <el-button
                class="border-btn"
                size="mini"
                @click="removeAllTerminal"
              >全部移除</el-button>
            </el-col>
          </div>

          <el-table
            :data="formData.devs"
            :max-height="400"
            size="small"
            header-cell-class-name="table-header"
            border
          >
            <el-table-column
              prop="terminalNo"
              label="终端编号"
              header-align="center"
            />
            <el-table-column
              prop="terminalName"
              label="终端名称"
              header-align="center"
            />
            <el-table-column
              label="终端所在地区"
              header-align="center"
            >
              <template #default="scope">
                <div>
                  <span v-if="scope.row.provinceName">{{ scope.row.provinceName }}</span>
                  <span v-if="scope.row.cityName">{{ scope.row.provinceName&&scope.row.cityName?' / ':'' }}{{ scope.row.cityName }}</span>
                  <span v-if="scope.row.areaName">{{ scope.row.cityName&&scope.row.areaName?' / ':'' }}{{ scope.row.areaName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="产品信息"
              header-align="center"
            >
              <template #default="scope">
                <div>
                  {{ scope.row.productPopularName }} - {{ scope.row.approvalNumber }} - {{ scope.row.packSpecs }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="terminalPrice"
              label="终端价（元）"
              header-align="center"
              align="center"
            />
            <el-table-column
              prop="agentName"
              label="渠道客户名称"
              header-align="center"
            />
            <el-table-column
              label="原配送费"
              header-align="center"
            >
              <template #default="scope">
                <div v-if="scope.row.computeMode==='固定价格'">
                  <span>{{ scope.row.distributePrice }}元</span><span> / {{ getLabel('sell_unit',scope.row.sellUnit) }}</span>
                </div>
                <div v-if="scope.row.computeMode==='终端价百分比'">
                  <span>{{ scope.row.distributePrice }}%</span><span>终端价</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="distributeServeNo"
              label="原配送服务编号"
              header-align="center"
            />
            <el-table-column
              label="操作"
              align="center"
            >
              <template #default="scope">
                <el-button
                  type="text"
                  @click="removeItem(scope.$index)"
                >移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
    </div>

    <!-- 添加终端 -->
    <add-terminal
      ref="addTerminalRef"
      @selectSuccess="terminalSelectSuccess"
    />

    <template #footer>
      <div
        class="dialog-footer"
        style="display:flex;justify-content:center;align-items:center;"
      >
        <el-button
          class="border-btn"
          size="small"
          @click="close"
        >取消</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          @click="confirm"
        >提交审核</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {defineComponent, getCurrentInstance, inject, reactive, ref, toRefs,} from 'vue'
import {crmStore} from '@CRM/store'
import addTerminal from './addTerminal.vue'
import {useRoute} from 'vue-router'

export default defineComponent({
  name: 'ChangeDistributeRelation',
  components: { addTerminal },
  emits: ['onSuccess'],
  setup(props, context) {
    const route = useRoute()
    const currentInstance = getCurrentInstance()
    const api = inject('api')
    const formRef = ref(null)
    var pricePopoverRef = ref(null)
    var addTerminalRef = ref(null)
    var reactiveData = reactive({
      proLoading: false,
      productOptions: [],
      distributorLoading: false,
      distributorOptions: [],
      distributeModeOptions:
        crmStore.getters['dictionary/getDictionary']['distributor_mode'],
      distributeDetail: null,
      formData: {
        productId: null,
        distributeDetailId: null,
        distributeId: null,
        rddType: '2',
        devs: [],
      },
      distributePriceInfo: null,
    })
    const productPass = (rule, value, callback) => {
      if (value) {
        callback()
      } else {
        callback(new Error('请选择配送产品信息'))
      }
    }
    const distributePass = (rule, value, callback) => {
      if (value) {
        callback()
      } else {
        if (reactiveData.formData.productId) {
          callback(new Error('请选择配送商'))
        } else {
          callback()
        }
      }
    }
    const distributePricePass = (rule, value, callback) => {
      if (value) {
        callback()
      } else {
        if (reactiveData.formData.distributeId) {
          callback(new Error('请选择配送费'))
        } else {
          callback()
        }
      }
    }
    var formRules = reactive({
      productId: [
        { required: true, validator: productPass, trigger: 'change' },
      ],
      distributeId: [
        { required: true, validator: distributePass, trigger: 'change' },
      ],
      distributeDetailId: [
        { required: true, validator: distributePricePass, trigger: 'change' },
      ],
      normal: [],
    })
    var formLabelWidth = ref(120)
    var dialogShow = ref(false)
    const open = (distributeDetail) => {
      console.log(distributeDetail)
      reactiveData.distributeDetail = distributeDetail

      // 获取该配送商下有效产品
      getDistributeProductList()
      dialogShow.value = true
      // 清除校验信息
      setTimeout(() => {
        formRef.value.clearValidate()
      }, 100)
    }
    const close = () => {
      dialogShow.value = false
      formRef.value.resetFields()
    }
    const confirm = () => {
      if (reactiveData.formData.devs.length === 0) {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: '请添加要变更的终端',
        })
        return
      }
      formRef.value.validate((valid) => {
        if (valid) {
          api.distributors
            .DISTRIBUTORS_RELATION_CHANGE_SUBMIT(reactiveData.formData)
            .then((res) => {
              if (res.code === 0) {
                context.emit('onSuccess')
                close()
              }
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
    const distributeModeChange = (val) => {
      // 厂家配送
      if (val === '1') {
        reactiveData.formData.distributeId = null
        reactiveData.formData.distributeDetailId = null
        reactiveData.formData.distributePrice = null
        reactiveData.distributePriceInfo = null
      }
    }
    const addTerminal = () => {
      var productBool = true
      var distributorBool = true
      var distributeServerBool = true
      formRef.value.validateField('productId', (err) => {
        if (err) {
          productBool = false
        }
      })
      if (!productBool) {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: '请选择配送产品信息',
        })
        return
      }
      formRef.value.validateField('distributeId', (err) => {
        if (err) {
          distributorBool = false
        }
      })
      if (!distributorBool) {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: '请选择配送商',
        })
        return
      }
      formRef.value.validateField('distributeDetailId', (err) => {
        if (err) {
          distributeServerBool = false
        }
      })
      if (!distributeServerBool) {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: '请选择配送费',
        })
        return
      }
      const objdata = {
        distributeId: reactiveData.distributeDetail.id,
        productInfo: reactiveData.productOptions.find(
          (p) => p.id === reactiveData.formData.productId
        ),
        distributePriceInfo: reactiveData.distributePriceInfo,
        distributeMode: reactiveData.formData.rddType,
      }
      addTerminalRef.value.open(objdata)
    }
    const terminalSelectSuccess = (list) => {
      reactiveData.formData.devs = list || []
    }
    const removeAllTerminal = () => {
      reactiveData.formData.devs = []
    }
    const removeItem = (index) => {
      reactiveData.formData.devs.splice(index, 1)
    }
    const selectChange = (id) => {
      var item = reactiveData.productOptions.find((p) => p.id)
      if (item) {
        reactiveData.currentSelect = item
        reactiveData.formData.sellUnit = item.sellUnit
      }
    }
    const productSelectChange = (val) => {
      console.log(val)
      reactiveData.formData.distributeId = null
      reactiveData.formData.distributeDetailId = null
      reactiveData.distributePriceInfo = null
      reactiveData.formData.distributePrice = null
      reactiveData.formData.sellUnit = ''
      reactiveData.formData.devs = []
      productForDistributorList(val)
    }
    const distributorChange = (val) => {
      console.log(val)
      reactiveData.formData.distributeDetailId = null
      reactiveData.distributePriceInfo = null
      reactiveData.formData.distributePrice = null
      reactiveData.formData.sellUnit = ''
      reactiveData.formData.devs = []
    }
    const distributePriceChange = (val) => {
      console.log(val)
      reactiveData.formData.distributeDetailId = null
      reactiveData.distributePriceInfo = null
      reactiveData.formData.distributePrice = null
      reactiveData.formData.sellUnit = ''
      reactiveData.formData.devs = []
    }
    // 获取该配送商下有效产品列表
    const getDistributeProductList = () => {
      api.distributors
        .DISTRIBUTORS_PRODUCT_LIST({
          distributeId: Number(route.query.id),
        })
        .then((res) => {
          if (res.code === 0) {
            reactiveData.productOptions = res.data.list
          }
        })
    }
    // 获取获取某产品配送商列表
    const productForDistributorList = (productId) => {
      api.distributors
        .PRODUCT_FOR_DISTRIBUTORS_LIST({
          productId: productId,
        })
        .then((res) => {
          if (res.code === 0) {
            reactiveData.distributorOptions = res.data.list
          }
        })
    }

    const selectDistributorChange = (id) => {
      var item = reactiveData.distributorOptions.find((p) => p.id)
      if (item) {
        console.log(item)
      }
    }
    const selectPrice = (val) => {
      console.log(val)
      if (
        val.id !== reactiveData.formData.distributeDetailId &&
        reactiveData.formData.distributeDetailId
      ) {
        removeAllTerminal()
      }
      reactiveData.distributePriceInfo = val
      reactiveData.formData.distributeDetailId = val.id
      reactiveData.formData.distributePrice = val.distributePrice
      reactiveData.formData.sellUnit = val.sellUnit
    }
    const priceFocus = (val) => {
      if (val) {
        pricePopoverRef.value.openPopover()
      } else {
        console.log(545)
      }
    }
    return {
      formRef,
      pricePopoverRef,
      addTerminalRef,
      ...toRefs(reactiveData),
      formRules,
      formLabelWidth,
      dialogShow,
      open,
      close,
      confirm,
      selectChange,
      selectDistributorChange,
      selectPrice,
      priceFocus,
      addTerminal,
      removeItem,
      removeAllTerminal,
      productSelectChange,
      terminalSelectSuccess,
      distributeModeChange,
      distributorChange,
      distributePriceChange,
    }
  },
})
</script>
